#!/usr/bin/env python3
"""
WebRTC信令服务器启动脚本
包含自动重启、监控和日志管理功能
"""

import subprocess
import time
import signal
import sys
import os
import psutil
import logging
from datetime import datetime

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('server.log'),
        logging.StreamHandler()
    ]
)

class ServerManager:
    def __init__(self):
        self.process = None
        self.restart_count = 0
        self.max_restarts = 10
        self.restart_delay = 5
        self.port = 5000
        self.host = '0.0.0.0'
        
    def start_server(self):
        """启动服务器"""
        try:
            logging.info("启动WebRTC信令服务器...")
            
            # 检查端口是否被占用
            if self.is_port_in_use():
                logging.error(f"端口 {self.port} 已被占用")
                return False
            
            # 启动服务器进程
            cmd = [sys.executable, 'app.py']
            self.process = subprocess.Popen(
                cmd,
                cwd=os.path.dirname(os.path.abspath(__file__)),
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True
            )
            
            # 等待服务器启动
            time.sleep(3)
            
            if self.process.poll() is None:
                logging.info(f"服务器已启动，PID: {self.process.pid}")
                logging.info(f"服务器地址: http://{self.host}:{self.port}")
                return True
            else:
                logging.error("服务器启动失败")
                return False
                
        except Exception as e:
            logging.error(f"启动服务器时出错: {e}")
            return False
    
    def stop_server(self):
        """停止服务器"""
        if self.process and self.process.poll() is None:
            logging.info("正在停止服务器...")
            
            # 尝试优雅停止
            try:
                self.process.terminate()
                self.process.wait(timeout=10)
            except subprocess.TimeoutExpired:
                logging.warning("服务器未在10秒内停止，强制终止")
                self.process.kill()
                self.process.wait()
            
            logging.info("服务器已停止")
    
    def restart_server(self):
        """重启服务器"""
        logging.info(f"重启服务器 (第 {self.restart_count + 1} 次)")
        self.stop_server()
        time.sleep(self.restart_delay)
        
        if self.start_server():
            self.restart_count = 0  # 重置重启计数
            return True
        else:
            self.restart_count += 1
            return False
    
    def is_port_in_use(self):
        """检查端口是否被占用"""
        try:
            import socket
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.bind((self.host, self.port))
                return False
        except OSError:
            return True
    
    def is_server_healthy(self):
        """检查服务器健康状态"""
        try:
            import requests
            response = requests.get(f"http://localhost:{self.port}/stats", timeout=5)
            return response.status_code == 200
        except:
            return False
    
    def get_server_stats(self):
        """获取服务器统计信息"""
        try:
            import requests
            response = requests.get(f"http://localhost:{self.port}/stats", timeout=5)
            if response.status_code == 200:
                return response.json()
        except:
            pass
        return None
    
    def monitor_server(self):
        """监控服务器状态"""
        logging.info("开始监控服务器...")
        
        while True:
            try:
                # 检查进程是否还在运行
                if self.process and self.process.poll() is not None:
                    logging.error("服务器进程已退出")
                    if self.restart_count < self.max_restarts:
                        if not self.restart_server():
                            logging.error(f"重启失败，已尝试 {self.restart_count} 次")
                            if self.restart_count >= self.max_restarts:
                                logging.error("达到最大重启次数，退出")
                                break
                    else:
                        logging.error("达到最大重启次数，退出")
                        break
                
                # 检查服务器健康状态
                if not self.is_server_healthy():
                    logging.warning("服务器健康检查失败")
                    if self.restart_count < self.max_restarts:
                        logging.info("尝试重启服务器...")
                        if not self.restart_server():
                            self.restart_count += 1
                
                # 打印统计信息
                stats = self.get_server_stats()
                if stats:
                    logging.info(f"服务器统计: {stats}")
                
                time.sleep(30)  # 每30秒检查一次
                
            except KeyboardInterrupt:
                logging.info("收到中断信号，正在停止服务器...")
                break
            except Exception as e:
                logging.error(f"监控过程中出错: {e}")
                time.sleep(10)
        
        self.stop_server()
        logging.info("服务器监控已停止")

def main():
    """主函数"""
    print("WebRTC信令服务器管理器")
    print("=" * 50)
    
    manager = ServerManager()
    
    # 设置信号处理
    def signal_handler(signum, frame):
        logging.info(f"收到信号 {signum}，正在停止服务器...")
        manager.stop_server()
        sys.exit(0)
    
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    # 启动服务器
    if manager.start_server():
        # 开始监控
        manager.monitor_server()
    else:
        logging.error("无法启动服务器")
        sys.exit(1)

if __name__ == "__main__":
    main() 